<template>
  <div class="medical-service-list-page">
    <div class="medical-service-list-header">
      <div class="search-row">
        <select v-model="searchField" class="search-select">
          <option value="projectName">项目名称</option>
          <option value="projectCode">项目编码</option>
          <option value="nationalCode">国家编码</option>
          <option value="financialCategory">财务分类</option>
        </select>
        <input v-model="search" class="search-input" :placeholder="`请输入${searchFieldName}`" />
        
        <!-- 价格区间搜索 -->
        <div class="price-range-search">
          <span class="price-label">价格区间：</span>
          <input v-model.number="priceRange.min" class="price-input" placeholder="最低价" type="number" step="0.01" min="0" />
          <span class="price-separator">-</span>
          <input v-model.number="priceRange.max" class="price-input" placeholder="最高价" type="number" step="0.01" min="0" />
        </div>
        
        <button class="search-btn" @click="onSearch" :disabled="loading">
          <svg v-if="!loading" viewBox="0 0 20 20" fill="none"><circle cx="9" cy="9" r="7" stroke="currentColor" stroke-width="2"/><path d="M15.5 15.5L13 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
          <span v-else>...</span>
        </button>
        <button class="reset-btn" @click="onReset" :disabled="loading">重置</button>
      </div>
      <div class="divider"></div>
      <div class="action-row">
        <button class="add-btn" @click="goEdit()" :disabled="loading">+ 新增诊疗项目</button>
        <button class="delete-btn" :disabled="!hasSelected || loading" @click="deleteSelected">删除选中</button>
      </div>
    </div>
    <div class="table-scroll-area">
      <table class="medical-service-table">
        <thead>
          <tr>
            <th><input type="checkbox" v-model="selectAll" @change="toggleAll" /></th>
            <th>序号</th>
            <th>财务分类</th>
            <th>项目编码</th>
            <th>国家编码</th>
            <th>项目名称</th>
            <th>项目内涵</th>
            <th>除外内容</th>
            <th>计价单位</th>
            <th>价格</th>
            <th>说明</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <!-- Loading 状态 -->
          <tr v-if="loading">
            <td colspan="12" style="text-align: center; padding: 40px;">
              <span>加载中...</span>
            </td>
          </tr>
          <!-- 无数据状态 -->
          <tr v-else-if="services.length === 0">
            <td colspan="12" style="text-align: center; padding: 40px; color: #999;">
              <span>暂无数据</span>
            </td>
          </tr>
          <!-- 正常数据 -->
          <tr v-else v-for="(item, idx) in services" :key="item.serviceId" :class="{alt: idx % 2 === 1}">
            <td><input type="checkbox" v-model="item.selected" /></td>
            <td>{{ (pagination.pageNum - 1) * pagination.pageSize + idx + 1 }}</td>
            <td>{{ item.financialCategory }}</td>
            <td>{{ item.projectCode }}</td>
            <td>{{ item.nationalCode }}</td>
            <td>{{ item.projectName }}</td>
            <td>{{ item.projectDescription }}</td>
            <td>{{ item.excludedContent }}</td>
            <td>{{ item.unitOfMeasure }}</td>
            <td>{{ item.price }}</td>
            <td>{{ item.notes }}</td>
            <td>
              <a href="#" @click.prevent="goEdit(item)">编辑</a>
              <span style="margin: 0 4px;">|</span>
              <a href="#" @click.prevent="deleteOne(item)">删除</a>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="pagination-bar" v-if="pagination.pageCount > 1">
      <button @click="gotoPage(pagination.pageNum-1)" :disabled="pagination.pageNum===1 || loading">上一页</button>
      <span>第 {{pagination.pageNum}} / {{pagination.pageCount}} 页 (共 {{pagination.total}} 条)</span>
      <button @click="gotoPage(pagination.pageNum+1)" :disabled="pagination.pageNum===pagination.pageCount || loading">下一页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMedicalServicesList, deleteMedicalService, batchDeleteMedicalServices } from '@/api/medicalServices'

const router = useRouter()

// 搜索条件
const search = ref('')
const searchField = ref('projectName')
const selectAll = ref(false)
const loading = ref(false)

// 价格区间搜索
const priceRange = reactive({
  min: null,
  max: null
})

// 搜索字段名称映射
const searchFieldNames = {
  projectName: '项目名称',
  projectCode: '项目编码',
  nationalCode: '国家编码',
  financialCategory: '财务分类'
}

const searchFieldName = computed(() => searchFieldNames[searchField.value])

// 分页数据
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  pageCount: 0
})

// 诊疗项目列表数据
const services = ref([])

// 获取诊疗项目列表
const fetchServicesList = async () => {
  loading.value = true
  try {
    const queryParams = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize
    }
    
    // 添加搜索条件
    if (search.value.trim()) {
      // 根据选择的字段进行精确搜索
      queryParams[searchField.value] = search.value.trim()
    }
    
    // 添加价格区间搜索
    if (priceRange.min !== null && priceRange.min !== '') {
      queryParams.minPrice = priceRange.min
    }
    if (priceRange.max !== null && priceRange.max !== '') {
      queryParams.maxPrice = priceRange.max
    }
    
    const response = await getMedicalServicesList(queryParams)
    
    if (response.flag) {
      const pageData = response.data
      services.value = pageData.records.map(item => ({
        ...item,
        selected: false
      }))
      pagination.total = pageData.total
      pagination.pageCount = pageData.pages || Math.ceil(pageData.total / pagination.pageSize)
    } else {
      ElMessage.error(response.message || '获取诊疗项目列表失败')
    }
  } catch (error) {
    console.error('获取诊疗项目列表失败:', error)
    ElMessage.error('获取诊疗项目列表失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 计算属性
const hasSelected = computed(() => services.value.some(item => item.selected))

// 搜索功能
const onSearch = () => {
  pagination.pageNum = 1
  fetchServicesList()
}

// 重置搜索
const onReset = () => {
  search.value = ''
  searchField.value = 'projectName'
  priceRange.min = null
  priceRange.max = null
  pagination.pageNum = 1
  fetchServicesList()
}

// 编辑诊疗项目
const goEdit = (item) => {
  if (item) {
    localStorage.setItem('editMedicalService', JSON.stringify(item))
    router.push(`/medical-info/treatment/edit/${item.serviceId}`)
  } else {
    localStorage.removeItem('editMedicalService')
    router.push('/medical-info/treatment/edit/new')
  }
}

// 删除单个诊疗项目
const deleteOne = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除诊疗项目"${item.projectName}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const response = await deleteMedicalService(item.serviceId)
    
    if (response.flag) {
      ElMessage.success('删除成功')
      fetchServicesList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除诊疗项目失败:', error)
      ElMessage.error('删除失败: ' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

// 批量删除选中的诊疗项目
const deleteSelected = async () => {
  const selectedItems = services.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的诊疗项目')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedItems.length} 个诊疗项目吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const ids = selectedItems.map(item => item.serviceId)
    const response = await batchDeleteMedicalServices(ids)
    
    if (response.flag) {
      ElMessage.success('批量删除成功')
      selectAll.value = false
      fetchServicesList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除诊疗项目失败:', error)
      ElMessage.error('批量删除失败: ' + (error.message || '网络错误'))
    }
  } finally {
    loading.value = false
  }
}

// 全选切换
const toggleAll = () => {
  services.value.forEach(item => {
    item.selected = selectAll.value
  })
}

// 分页跳转
const gotoPage = (page) => {
  if (page >= 1 && page <= pagination.pageCount) {
    pagination.pageNum = page
    fetchServicesList()
  }
}

// 页面初始化
onMounted(() => {
  fetchServicesList()
})
</script>

<style scoped>
.medical-service-list-page {
  width: 100%;
  height: 100vh;
  background: #f5f6fa;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.medical-service-list-header {
  background: #fff;
  padding: 24px 32px;
  border-bottom: 1px solid #e5e6eb;
  flex-shrink: 0;
}

.search-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  width: 100%;
  gap: 12px;
  flex-wrap: wrap;
}

.action-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: 0;
  padding-left: 0;
}

.search-select {
  height: 38px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 12px;
  font-size: 16px;
  background: #fff;
  color: #333;
  min-width: 120px;
}

.search-input {
  flex: 1;
  max-width: 200px;
  height: 38px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 16px;
  font-size: 16px;
  background: #fff;
}

.price-range-search {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left: 12px;
}

.price-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.price-input {
  width: 80px;
  height: 38px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 8px;
  font-size: 14px;
  background: #fff;
  text-align: center;
}

.price-separator {
  color: #666;
  font-size: 14px;
}

.search-btn, .reset-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 38px;
  padding: 0 16px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  min-width: 80px;
}

.reset-btn {
  background: #909399;
}

.search-btn:disabled, .reset-btn:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}

.search-btn svg {
  width: 18px;
  height: 18px;
  display: block;
}

.divider {
  width: 100%;
  height: 1px;
  background: #e5e6eb;
  margin: 0 0 18px 0;
}

.add-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 18px;
  font-size: 15px;
  cursor: pointer;
  margin-right: 10px;
  box-shadow: none;
}

.delete-btn {
  background: #f56c6c;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 18px;
  font-size: 15px;
  cursor: pointer;
  box-shadow: none;
}

.delete-btn:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}

.table-scroll-area {
  flex: 1;
  overflow: auto;
  background: #fff;
  margin: 0 24px;
  border: 1px solid #e5e6eb;
  border-radius: 4px;
}

.medical-service-table {
  width: 100%;
  border-collapse: collapse;
  background: #fff;
  margin-top: 0;
  border-radius: 0;
  overflow: hidden;
  box-shadow: none;
}

.medical-service-table tr.alt {
  background: #f7f9fb;
}

.medical-service-table tr {
  background: #fff;
}

.medical-service-table th, .medical-service-table td {
  border-bottom: 1px solid #ececec;
  padding: 12px 8px;
  text-align: center;
  font-size: 14px;
  color: #222;
  background: transparent;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.medical-service-table th {
  background: #f7f8fa;
  color: #34495e;
  font-weight: 700;
  border-bottom: 2px solid #e5e6eb;
  font-size: 14px;
  position: sticky;
  top: 0;
  z-index: 10;
}

.medical-service-table tbody tr:hover td {
  background: inherit !important;
}

.medical-service-table tr:last-child td {
  border-bottom: none;
}

.medical-service-table a {
  color: #409eff;
  text-decoration: none;
  cursor: pointer;
  font-size: 14px;
  margin: 0 2px;
  padding: 2px 6px;
  border-radius: 4px;
  transition: background 0.18s;
}

.medical-service-table a:hover {
  background: #eaf3ff;
  text-decoration: underline;
}

.pagination-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 18px;
  margin: 24px 0;
  flex-shrink: 0;
}

.pagination-bar button {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 4px 18px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}

.pagination-bar button:disabled {
  background: #e0e0e0;
  color: #aaa;
  cursor: not-allowed;
}
</style>
